package com.hireceivecard.service.Impl;

import com.hireceivecard.config.AppException;
import com.hireceivecard.config.RedisOperator;
import com.hireceivecard.pojo.Result;
import com.hireceivecard.pojo.SendCode;
import com.hireceivecard.pojo.WangYi;
import com.hireceivecard.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:短信验证码服务
 * @Author 2742866928@qq.com
 * @Date: 2024/4/15 下午8:04
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    SendCode sendCode;
    @Autowired
    RedisOperator redisOperator;

    /**
     * 获取短信验证码
     * @param mobilePhone
     * @param code
     * @return
     */
    @Override
    public Result getaptcha(String mobilePhone, String code) {
        WangYi wangYi=null;
        try {
            wangYi= sendCode.sendCode(mobilePhone, code);
        } catch (Exception e) {
            log.info("secondValidateCaptcha"+e.getMessage());
            throw new AppException(e.getMessage());
        }
        redisOperator.set("sms1"+mobilePhone,code,5*60);
        return Result.success(wangYi,"发送验证码成功！");
    }

    /**
     * 校验短信验证码
     * @param mobilePhone
     * @param captcha
     * @return
     */
    @Override
    public boolean validateCaptcha(String mobilePhone, String captcha) {
        String correctCode = redisOperator.get("sms1" + mobilePhone);
        if (correctCode == null) {
            AppException.getAppException("验证码已过期",500);
            return false;
        }
        if (!correctCode.equals(captcha)) {
            AppException.getAppException("验证码错误",500);
            return false;
        }
        redisOperator.del("sms1" + mobilePhone);
        return true;
    }
}
